//
//  ConfirmDelAccountVC.swift
//  ezyform
//
//  Created by Moennig Q on 8/2/2022.
//  Copyright © 2022 Client.Solution Pty Ltd. All rights reserved.
//

import UIKit

class ConfirmDelAccountVC: ModelBaseViewController {
    var timer : Timer?
    var countDownKey: String = ""
    var countDownSeconds: Int = 0
    
    let customView = ConfirmDelAccountView()
    //
    var deleteFaildFlag: Bool = false
    override func viewDidLoad() {
        super.viewDidLoad()
        self.initUI()
    }
    func initUI(){
        self.view = self.customView
        self.customView.setTitle(R.string.localizable.deleteAccount())
        
        self.customView.closeBtn.addTarget(self, action: #selector(dismissVC), for: UIControl.Event.touchUpInside)
        self.customView.sendVerificationCodeClosure = { [weak self] in
            guard let strongSelf = self else { return  }
            strongSelf.sendVerificationCode()
        }
        self.customView.confirmClosure = { [weak self](code) in
            guard let strongSelf = self else { return  }
            strongSelf.confirmDelAccount(code)
        }
        self.customView.backToPreClosure = { [weak self] in
            guard let strongSelf = self else { return  }
            strongSelf.backToPre()
        }
    }
    override func backToPre() {
        if deleteFaildFlag {
            self.navigationController?.popToRootViewController(animated: true)
        }else{
            self.navigationController?.popViewController(animated: false)
        }
    }
    @objc func startTimer() {
        self.countDownSeconds = APPConfig.VerificationCodeInterval
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(refreshCountDown), userInfo: nil, repeats: true)
        //调用fire()会立即启动计时器
        timer!.fire()
    }
    @objc func stopTimer() {
        if timer != nil {
            timer!.invalidate() //销毁timer
            timer = nil
        }
    }
   
    @objc func refreshCountDown(){
        if self.countDownSeconds == 0 {
            self.customView.setResendBtnTitle("Resend",enabled: true)
            self.stopTimer()
        }else{
            self.countDownSeconds = self.countDownSeconds - 1
            self.customView.setResendBtnTitle("Resend After \(self.countDownSeconds)s",enabled: false)
        }
    }
    func sendVerificationCode(){
        if  Connectivity.isConnectedToInternet {
            let viewModel = LoginService()
            viewModel.setBlockAfterNetwork { (result , _)in
                //发送成功后，开启Resend倒计时timer
                self.startTimer()
            } errorBlock: { (code,error)  in
                self.customView.sendBtn.isEnabled = true
                Tool().showErrorInfo(code, error)
            }
            //
            viewModel.sendVerificationCode()
        }else{
            Tool().showFailureInfo()
        }
    }
    func confirmDelAccount(_ code: String){
        if  Connectivity.isConnectedToInternet {
            let viewModel = LoginService()
            viewModel.setBlockAfterNetwork { (result , _) in
                ModelViewUtil.shared.hideLoadingView()
                //删除成功时的提示,点击OK，返回登录界面且清空账号信息
                Tool().clearAccountInfo()
                self.customView.showSuccessView()
            } errorBlock: { (code,error) in
                ModelViewUtil.shared.hideLoadingView()
                if code.contains("405"){//验证码是无效的
                    //无效验证码的提示
                    self.customView.verificationCodeTextfield.showInvalidMsg( R.string.localizable.invalidCode())
                }else if code.contains(APICustomStatusCode.InvalidToken.rawValue){//账号不存在，直接退出登录
                    Tool().showErrorInfo(code, error)
                }else{//删除失败显示失败原因，点击返回按钮发挥到Me界面
                    self.customView.showFaildView(faildReason: error)
                    self.deleteFaildFlag = true
                }
            }
            //add Loading view
            ModelViewUtil.shared.showLoadingView("Deleting account...")
            //
            viewModel.deleteAccount(code)
        }else{
            Tool().showFailureInfo()
        }
    }
}
